﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using DotaHelp.Helpers;
using System.ServiceModel.Syndication;

namespace DotaHelp.Controllers
{
    public class UpgradesController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            model.Dispose();
            
        }

        public ActionResult List(int? page, string orderBy)
        {
			var upgrades = model.Upgrades.Include("UpgradesItems").Include("UpgradesItems.Skill").Include("Hero").Where(p => !p.IsDeleted);
            return View(upgrades.ByPage(page, orderBy, p => p.Raiting, p => p.Date, ViewData, HttpContext).ToArray());
        }


        public ActionResult Add(int id)
        {
            var hero = model.Heroes.Include("Skills").First(h => h.Id == id);
            ViewBag.Skills = hero.Skills.OrderBy(s => s.Id).Where(s => s.Parent == null).Union(model.Skills.Where(s => s.Id == 0)).ToArray();
            ViewBag.Hero = hero;
            ViewBag.UserName = Request.GetUserName();
            return View();
        }

        [HttpPost]
        public ActionResult Add(int heroId, string author, string comment, string password, string skills)
        {
            Response.SaveUserName(author);

            var u = new Upgrade()
            {
                IpAddress = Request.ServerVariables["REMOTE_ADDR"],
                Date = DateTime.UtcNow.NowByAstana(),
                Raiting = 0,
                Author = ControllerContext.HttpContext.PrepareUserName(author),
                Comment = comment,
                HeroId = heroId,
                Password = password
            };

            int position = 1;
            foreach (var skill in skills.Split(','))
            {
                u.UpgradesItems.Add(new UpgradesItem() { SkillId = int.Parse(skill), Position = position++ });
            }

            model.Upgrades.AddObject(u);
            model.SaveChanges();


            return RedirectToRoute("Upgrade", new { id = u.Id });
        }

        [Authorize(Roles = "Admin")]
        public void Delete(int id)
        {
            var p = model.Upgrades.First(i => i.Id == id);
            p.IsDeleted = true;
            model.SaveChanges();
        }

        public ActionResult ChooseHero()
        {
            return View(model.Heroes);
        }

        [Sitemap(typeof(Upgrade), "Date")]
        public ActionResult Details(int id)
        {
			var upgrade = model.Upgrades.Include("UpgradesItems").Include("UpgradesItems.Skill").Include("Hero").First(p => p.Id == id);
            return View(upgrade);
        }
                
        public ActionResult ListForHero(int heroId)
        {
			var list = model.Upgrades
				.Include("UpgradesItems")
				.Include("UpgradesItems.Skill")
				.Where(p => !p.IsDeleted)
				.Where(p => p.HeroId == heroId)
				.OrderByDescending(a => a.Raiting)
				.OrderBy(a => a.Date);

            return Request.IsAjaxRequest() ? (ActionResult)PartialView(list) : View(list);
        }

        [ChildActionOnly]
        public string Rating(int id, bool isPlus)
        {
            var upgrade = model.Upgrades.First(p => p.Id == id);
            upgrade.Raiting += isPlus ? 1 : -1;
            model.SaveChanges();
            return upgrade.Raiting.ToString();
        }

        
        public ActionResult One(int id, bool showHero = true, bool isSmall = true)
        {
            ViewData["ShowHero"] = showHero;
            if (isSmall) ViewData["Small"] = true;

			var upgrade = model.Upgrades.Include("UpgradesItems")
				.Include("UpgradesItems.Skill").Include("Hero").FirstOrDefault(p => p.Id == id);
            return upgrade != null ? (ActionResult)PartialView(upgrade)
                : new ContentResult() { Content = "u" + id };
        }

		[ChildActionOnly]
		public ActionResult OneObject(Upgrade upgrade, bool showComments = false)
		{
			ViewData["ShowHero"] = true;
			ViewData["ShowCaption"] = true;
			ViewData["ShowComments"] = showComments;
			return PartialView("One", upgrade);
		}

        [ChildActionOnly]
        [Rss]
        public IEnumerable<SyndicationItem> Rss()
        {
            var url = new UrlHelper(Request.RequestContext);
            
            foreach (var c in model.Upgrades.OrderByDescending(_ => _.Date).Take(50))
            {
                yield return new SyndicationItem("Прокачка", c.Comment, new Uri(url.GetBaseUrl(), url.Action("Details", "Upgrades", new { id = c.Id })), "r" + c.Id, c.Date);
            }
        } 
    }
}
